//
//  HomeViewController.m
//  Feel_at_home
//
//  Created by dlios on 15/9/23.
//  Copyright © 2015年 Feel_at_home. All rights reserved.
//

#import "HomeViewController.h"
#import <AFNetworking.h>
#import "HomeModel.h"
#import "HomeViewCell.h"
#import <UIImageView+WebCache.h>
#import <MJRefresh.h>
#import <HTTPTOOL.h>
#import "HoneView.h"
#import "HomeDataViewController.h"
#import <MBProgressHUD.h>
#import "WidthAndHeight.pch"
@interface HomeViewController ()<UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate,UIScrollViewAccessibilityDelegate>


@property (nonatomic,strong) UITableView *tableview;
@property (nonatomic,strong) UIScrollView *barscrollview;
@property (nonatomic,strong) UIScrollView *scrollview;
@property (nonatomic,strong) NSMutableArray *buttonArr;
@property (nonatomic,strong) NSMutableArray *tableviewArr;
@property (nonatomic,strong) NSMutableArray *butclickArr;
@property (nonatomic,strong) NSMutableArray *cellArr;
@property (nonatomic,strong) NSMutableArray *cellArr1;
@property (nonatomic,strong) NSMutableArray *idArr;
@property (nonatomic,copy) NSString *idcount;
@property (nonatomic,assign) NSInteger i;
@property (nonatomic,assign) NSInteger number;
@property (nonatomic,assign) NSInteger number1;
@property (nonatomic,strong) NSMutableArray *headarr;
@property (nonatomic,retain) MBProgressHUD *loading;

@property (nonatomic, retain) NSString *jingpinPath;
@property (nonatomic, retain) NSString *qitaPath;
@property (nonatomic, retain) NSString *buttonPath;
@property (nonatomic, retain) NSString *lunboPath;
@property (nonatomic, assign) BOOL filg;

@end

@implementation HomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self tableSubView];
    [self ButDataHand];
    [self barSubView];
    [self DataHand];
    self.title = @"心情家居";
    self.filg = NO;
    
     self.cellArr = [NSMutableArray array];
    
    self.loading = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    //提示文本
    self.loading.labelText = @"正在加载...";
    //    //是否有遮罩
    //        self.loading.dimBackground = YES;
    
    /* 获取要保存的路径(哪一个文件夹),文件保存到Documents 文件中 */
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
    /* 2. 创建文件路径
     * 数组存入本地,若文件名没有后缀,默认市XML 格式
     */
    self.jingpinPath = [cachePath stringByAppendingPathComponent:@"jingpin.plist"];
    self.qitaPath    = [cachePath stringByAppendingPathComponent:@"qita.plist"];
    self.buttonPath  = [cachePath stringByAppendingPathComponent:@"button.plist"];
    self.lunboPath   = [cachePath stringByAppendingPathComponent:@"lunbo.plist"];
  
}

//头部标题
-(void)barSubView   
{
    self.barscrollview = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width,self.view.frame.size.height*0.05)];
    self.barscrollview.contentSize = CGSizeMake(self.view.frame.size.width, 0);
    [self.view addSubview:self.barscrollview];
    self.butclickArr = [NSMutableArray array];
    
    for (int i = 0; i <self.buttonArr.count; i++) {
       
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(self.view.frame.size.width / 6 * i, 0, self.view.frame.size.width / 6, 25);
        [self.barscrollview addSubview:button];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [button setTitle:self.buttonArr[i] forState:UIControlStateNormal];
        button.tag = i + 1;
        [self.butclickArr addObject:button];
        [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        if (i == 0) {
            [button setTitleColor:[UIColor colorWithRed:0.434 green:1.000 blue:0.167 alpha:1.000] forState:UIControlStateNormal];
        }
    }
    
}

- (void)tableSubView
{
    [self DataHead];
    self.scrollview = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 30, self.view.frame.size.width, self.view.frame.size.height )];
    self.scrollview.scrollEnabled = YES;
    self.scrollview.pagingEnabled = YES;
    self.scrollview.delegate = self;
    self.scrollview.contentSize = CGSizeMake(self.view.frame.size.width*self.buttonArr.count, self.view.frame.size.height);
     self.scrollview.showsVerticalScrollIndicator = NO;/* 纵向的指示器 */
    self.scrollview.bounces = NO;
    
    [self.view addSubview:self.scrollview];
    
    
    self.tableviewArr = [NSMutableArray array];
    
    for (int i = 0; i < self.buttonArr.count; i++) {
        if (i == 0) {
            self.tableview = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height + 30) style:UITableViewStyleGrouped];
            self.tableview.showsVerticalScrollIndicator = NO;
            [self.scrollview addSubview:self.tableview];
            self.tableview.dataSource = self;
            self.tableview.separatorStyle = NO;
            self.tableview.delegate = self;
            self.tableview.contentInset = UIEdgeInsetsMake(-30, 0, 0, 0);//偏量
            self.tableview.backgroundColor = [UIColor clearColor];
            self.tableview.header =[MJRefreshGifHeader headerWithRefreshingBlock:^{
                
                [self.tableview.header beginRefreshing];
                self.number = 0;
                [self DataHand];
               
                
            }];
            self.tableview.footer = [MJRefreshAutoGifFooter footerWithRefreshingBlock:^{
                
                [self.tableview.footer beginRefreshing];
                self.number += 20;
                [self DataHand];
                
            }];
            
        }
        else{
            UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(self.view.frame.size.width * i, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
            [self.scrollview addSubview:tableView];
            tableView.separatorStyle = NO;
            tableView.dataSource = self;
            tableView.delegate = self;
            tableView.backgroundColor = [UIColor clearColor];
            tableView.tag = 1 + i;
            [self.tableviewArr addObject:tableView];
            tableView.header = [MJRefreshGifHeader headerWithRefreshingBlock:^{
                self.filg = NO;
                [tableView.header beginRefreshing];
                self.number1 = 0;
                [self OtherDate];
            }];
            
            tableView.footer = [MJRefreshAutoGifFooter footerWithRefreshingBlock:^{
                self.filg = YES;
                [tableView.footer beginRefreshing];
                self.number1 += 20;
                self.filg = YES;
                [self OtherDate];
            }];
            
        }
    }
 
 
}

#pragma button文字解析,id值
- (void)ButDataHand
{

    NSString *Url = @HomeButton;
    [HTTPTOOL GETWithURL:Url body:nil httpHead:nil responseStyle:JSON success:^(id result) {
        
        NSDictionary *dic = result;
        /* 3. 写入文件 */
        [dic writeToFile:self.buttonPath atomically:YES];
        self.buttonArr = [NSMutableArray array];
        self.idArr = [NSMutableArray array];
        NSArray *arr= [[dic objectForKey:@"data"]objectForKey:@"channels"];
        
        for (NSDictionary *dic1 in arr) {
            
            NSString *str = [dic1 objectForKey:@"name"];
            NSString *str1 = [dic1 objectForKey:@"id"];
            [self.buttonArr addObject:str];
            [self.idArr addObject:str1];
        }
        
        [self barSubView];
        [self tableSubView];
        
    } fail:^(NSError *error) {
        
        NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:self.buttonPath];
        self.buttonArr = [NSMutableArray array];
        self.idArr = [NSMutableArray array];
        NSArray *arr= [[dic objectForKey:@"data"]objectForKey:@"channels"];
        
        for (NSDictionary *dic1 in arr) {
            
            NSString *str = [dic1 objectForKey:@"name"];
            NSString *str1 = [dic1 objectForKey:@"id"];
            [self.buttonArr addObject:str];
            [self.idArr addObject:str1];
        }

            [self barSubView];
            [self tableSubView];
    
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请检查您的网络" preferredStyle:UIAlertControllerStyleAlert];
            /* 添加 action */
            UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                
            }];
            [alert addAction:action1];
            /* VC模态推出 alert 界面 */
            [self presentViewController:alert animated:YES completion:^{
                
                [self.loading hide:YES];
            }];

        
    }];
}

//主页
- (void)DataHand
{
 
    NSString *Url =[NSString stringWithFormat: @HomeDate,self.number];
    
    [HTTPTOOL GETWithURL:Url body:nil httpHead:nil responseStyle:JSON success:^(id result) {
          NSDictionary *dic = result;
        /* 3. 写入文件 */
        [dic writeToFile:self.jingpinPath atomically:YES];

        NSMutableArray *arr = [[dic objectForKey:@"data"]objectForKey:@"items"];
        
        for (NSDictionary *dic1 in arr) {
            
            HomeModel *home = [[HomeModel alloc]init];
            [home setValuesForKeysWithDictionary:dic1];
            [self.cellArr addObject:home];
        }
        
        [self.tableview reloadData];
        [self.tableview.header endRefreshing];
        [self.tableview.footer endRefreshing];
        [self.loading hide:YES];
        
    } fail:^(NSError *error) {
        /* 1. 找到文件路径(不是文件夹路径) */

        NSDictionary *dic1 = [NSDictionary dictionaryWithContentsOfFile:self.jingpinPath];
       
        NSMutableArray *arr = [[dic1 objectForKey:@"data"]objectForKey:@"items"];

        for (NSDictionary *dic in arr) {
            
            HomeModel *home = [[HomeModel alloc]init];
            [home setValuesForKeysWithDictionary:dic];
            [self.cellArr addObject:home];
        }
            
            [self.tableview reloadData];
            [self.tableview.header endRefreshing];
            [self.tableview.footer endRefreshing];
            [self.loading hide:YES];
            
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请检查您的网络" preferredStyle:UIAlertControllerStyleAlert];
            /* 添加 action */
            UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                
            }];
            [alert addAction:action1];
            /* VC模态推出 alert 界面 */
            [self presentViewController:alert animated:YES completion:^{
                
                [self.loading hide:YES];
            }];

        
    }];
}
//其它主页
- (void)OtherDate
{
    UITableView *tab = [self.tableviewArr objectAtIndex:self.i];
//    self.loading = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//    //提示文本
//    self.loading.labelText = @"正在加载...";
    //    //是否有遮罩
    //        self.loading.dimBackground = YES;
    
    NSString *Url = [NSString stringWithFormat:@HomeOtherData, self.idcount,self.number1];
  
    [HTTPTOOL GETWithURL:Url body:nil httpHead:nil responseStyle:JSON success:^(id result) {
        NSDictionary *dic = result;
        /* 3. 写入文件 */
        [dic writeToFile:self.buttonPath atomically:YES];
        
        if (self.filg == NO) {
            self.cellArr1 = [NSMutableArray array];
        }
     
        NSMutableArray *arr = [[dic objectForKey:@"data"]objectForKey:@"items"];
        
        for (NSDictionary *dic in arr) {
            
            HomeModel *home = [[HomeModel alloc]init];
            [home setValuesForKeysWithDictionary:dic];
            [self.cellArr1 addObject:home];
        }
        [self.loading hide:YES];
        [tab reloadData];
        [tab.header endRefreshing];
        [tab.footer endRefreshing];
        

        
    } fail:^(NSError *error) {
        NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:self.qitaPath];
        
        NSMutableArray *arr = [[dic objectForKey:@"data"]objectForKey:@"items"];
        
        for (NSDictionary *dic in arr) {
            
            HomeModel *home = [[HomeModel alloc]init];
            [home setValuesForKeysWithDictionary:dic];
            [self.cellArr1 addObject:home];
        }
        
            [tab reloadData];
            [tab.header endRefreshing];
            [tab.footer endRefreshing];
            [self.loading hide:YES];

            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请检查您的网络" preferredStyle:UIAlertControllerStyleAlert];
            /* 添加 action */
            UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                
            }];
            [alert addAction:action1];
            /* VC模态推出 alert 界面 */
            [self presentViewController:alert animated:YES completion:^{
                
                [self.loading hide:YES];
            }];
        
    }];

}
#pragma 轮播图解析
- (void)DataHead
{
    
    NSString *Url = @HomeHeadData;
    
    [HTTPTOOL GETWithURL:Url body:nil httpHead:nil responseStyle:JSON success:^(id result) {

        NSDictionary *dic1 = result;
        /* 3. 写入文件 */
        [dic1 writeToFile:self.lunboPath atomically:YES];

        NSMutableArray *arr = [[dic1 objectForKey:@"data"]objectForKey:@"banners"];
        self.headarr = [NSMutableArray array];
        for (NSDictionary *dic in arr) {

            NSString *str1 = [dic objectForKey:@"image_url"];
            [self.headarr addObject:str1];
            
        }
        
        [self.tableview reloadData];
        self.loading.hidden = YES;

    } fail:^(NSError *error) {
        NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:self.lunboPath];
        
        NSMutableArray *arr = [[dic objectForKey:@"data"]objectForKey:@"banners"];
        self.headarr = [NSMutableArray array];
        for (NSDictionary *dic in arr) {
            
            NSString *str1 = [dic objectForKey:@"image_url"];
            [self.headarr addObject:str1];
            
        }
            
            [self.tableview reloadData];
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请检查您的网络" preferredStyle:UIAlertControllerStyleAlert];
            /* 添加 action */
            UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                
            }];
            [alert addAction:action1];
            /* VC模态推出 alert 界面 */
            [self presentViewController:alert animated:YES completion:^{
                
                [self.loading hide:YES];
            }];
        
    }];

}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
   if (tableView.frame.origin.x == 0) {
    return self.cellArr.count;
   }else
   {
       return self.cellArr1.count;
   }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.frame.origin.x == 0) {
     HomeViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse"];
    if (cell == nil) {
        
        cell = [[HomeViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"reuse"];
    }
    cell.homemodel = [self.cellArr objectAtIndex:indexPath.row];
        
    return cell;
    }else
    {
        HomeViewCell *cell1 = [tableView dequeueReusableCellWithIdentifier:@"reuse"];
        if (cell1 == nil) {
           
            cell1 = [[HomeViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"reuse"];
        }
        cell1.homemodel = [self.cellArr1 objectAtIndex:indexPath.row];
        
        return cell1;

    }
}
//进入详情页
 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (tableView == self.tableview) {
        HomeDataViewController *homedata = [[HomeDataViewController alloc]init];
        
        NSArray *(^block)(NSArray *) = ^(NSArray *arr)
        {
            HomeModel *home = [[HomeModel alloc]init];
            
            home = self.cellArr[indexPath.row];
            
            NSString *str1 = home.title;
            NSString *str2 = home.url;
            
            arr = [NSMutableArray arrayWithObjects:str1,str2,nil];
            
            return arr;
        };
        homedata.block1 = block;
        
        [self.navigationController pushViewController:homedata animated:YES];
    }else
    {
        HomeDataViewController *homedata = [[HomeDataViewController alloc]init];
        
        NSArray *(^block)(NSArray *) = ^(NSArray *arr)
        {
            HomeModel *home = [[HomeModel alloc]init];
            
            home = self.cellArr1[indexPath.row];
            
            NSString *str1 = home.title;
            NSString *str2 = home.url;
            
            arr = [NSMutableArray arrayWithObjects:str1,str2,nil];
            
            return arr;
        };
        homedata.block1 = block;
        
        [self.navigationController pushViewController:homedata animated:YES];
    }
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 200;
}
/* 分区头部高度 */
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
        if (tableView.frame.origin.x == 0) {
            if (section == 0) {
                
                return 170;
            }
    }
    return 0;
    
}
//轮播图
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    if (section == 0) {
        if (self.headarr.count!= 0) {
            HoneView *head = [[HoneView alloc]initWithFrame:CGRectMake(0, 0, VCWIDTH, 170)];
            
            head.picarr = self.headarr;
            
    
            [self.tableview addSubview:head];
            
            return head;
        }
        return nil;
        
    }else{
        
        return nil;
    }
  
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (scrollView == self.scrollview) {
        NSInteger i = scrollView.contentOffset.x / self.view.frame.size.width;
        UIButton *button = [self.butclickArr objectAtIndex:i];
    
    if (i == 0) {
        [self.scrollview setContentOffset:CGPointMake(0, 0) animated:YES];
    }else
    {
        [self.scrollview setContentOffset:CGPointMake(i*VCWIDTH, 0) animated:YES];
    }
        [self buttonClick:button];

    }
}
- (void)buttonClick: (UIButton *)button
{
    [self buttonchange:button];
    if (button.tag == 1) {
        self.scrollview.contentOffset = CGPointMake(0, 0);
        [button setTitleColor:[UIColor colorWithRed:0.515 green:1.000 blue:0.120 alpha:1.000] forState:UIControlStateNormal];
        [self DataHand];
    }
    else
    {
        self.scrollview.contentOffset = CGPointMake(VCWIDTH * (button.tag-1), 0);
        self.i = button.tag - 2;
     
        self.idcount = self.idArr[button.tag - 1];
        self.number1 = 0;
        self.filg = NO;
        [self OtherDate];
        [button setTitleColor:[UIColor colorWithRed:0.520 green:1.000 blue:0.455 alpha:1.000] forState:UIControlStateNormal];
    }
    
}
- (void)buttonchange:(UIButton *)button
{
    for (UIButton *but in self.butclickArr) {
        [but setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    }

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
